package controllers

import (
	models "comment/models"
	//	"fmt"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/tealeg/xlsx"
)

type BadwordController struct {
	BaseController
}

//badwords and search
func (c *BadwordController) Index() {
	c.Data["PageTitle"] = "黑名单列表"
	var query = make(map[string]string)
	StatusList := map[int]string{0: "是否启用", 1: "是", 2: "否"}
	if v := c.GetString("name"); v != "" {
		//模糊匹配
		query["name__icontains"] = v
		c.Data["name"] = v
	}
	if v := c.GetString("creatorname"); v != "" {
		query["creatorname"] = v
		c.Data["creator"] = v
	}
	if v := c.GetString("modifiername"); v != "" {
		query["modifier"] = v
		c.Data["modifier"] = v
	}
	if v := c.GetString("status"); v != "" && v != "0" {
		query["status"] = v
	}
	if v := c.GetString("createbtime"); v != "" {
		query["CreateTime__gte"] = v
		c.Data["createbtime"] = v
	}
	if v := c.GetString("createetime"); v != "" {
		query["CreateTime__lte"] = v
		c.Data["createetime"] = v
	}

	if v := c.GetString("modifybtime"); v != "" {
		query["ModifyTime__gte"] = v
		c.Data["modifybtime"] = v
	}

	if v := c.GetString("modifyetime"); v != "" {
		query["ModifyTime__lte"] = v
		c.Data["modifyetime"] = v
	}

	pageNo, _ := c.GetInt("PageNo")
	if pageNo == 0 {
		pageNo = 1
	}
	sizePage := c.GetString("SizePage")
	s, _ := strconv.Atoi(sizePage)
	if s == 0 {
		s = 10
	}
	c.Data["SizePage"] = s
	c.Data["Page"] = models.PageBadwords(pageNo, s, query, nil)
	c.Data["StatusList"] = StatusList
	c.Data["Query"] = query
	Status, _ := strconv.Atoi(query["status"])
	c.Data["Status"] = Status
	c.Layout = "layout/layout.html"
	c.TplName = "badword/index.html"
}

//add badwords
func (c *BadwordController) Create() {
	id := c.Ctx.Input.Param(":id")
	if intid, err := strconv.Atoi(id); err == nil {
		result, _ := models.GetCommentByID(intid)
		c.Data["json"] = result
	}
	c.ServeJSON()
}

//update badwords
func (c *BadwordController) Update() {
	id := c.Ctx.Input.Param(":id")
	name := c.GetString("name")
	userId := c.GetSession("userId")
	status := c.GetString("status")
	if intid, err := strconv.Atoi(id); err == nil {
		badword := models.Badword{Id: intid}
		tmp := badword.Status
		if status, err := strconv.Atoi(status); err == nil {
			tmp = int8(status)
		}
		badword.Name = name
		badword.Status = tmp
		if id, ok := userId.(int); ok {
			badword.Modifier = id
		}
		badword.ModifyTime = time.Now()
		errs := models.UpdateBadwordById(&badword)
		if errs == nil {
			c.Redirect("/badword/index", 302)
		} else {
			flash := beego.NewFlash()
			flash.Error("敏感词修改失败")
		}
	}

}

//import badwords
func (c *BadwordController) Import() {
	c.Data["PageTitle"] = "敏感词导入"
	c.Layout = "layout/layout.html"
	c.TplName = "badword/import.html"
}

func (c *BadwordController) Add() {
	c.Data["PageTitle"] = "敏感词导入"
	_, fh, err := c.GetFile("badword")
	if err == nil {
		fileName := fh.Filename
		arr := strings.Split(fileName, ":")
		if len(arr) > 1 {
			index := len(arr) - 1
			fileName = arr[index]
		}
		strPath := path.Join("/uploads/"+time.Now().Format("20060102")+"/", fileName)
		_, err1 := os.Stat(strPath)

		if err1 != nil && os.IsNotExist(err1) {
			os.MkdirAll("/uploads/"+time.Now().Format("20060102"), os.ModePerm) //生成多级目录
		}
		c.SaveToFile("badword", path.Join(strPath))
		xlFile, erro := xlsx.OpenFile(strPath)
		if erro != nil {
			c.Ctx.WriteString("打开文件失败")
		}
		userId := c.GetSession("userId")
		var total = int64(0)    //总数
		var dupCount = int64(0) //重复数
		var names string
		for _, sheet := range xlFile.Sheets {
			if sheet.MaxRow != 0 {
				for _, row := range sheet.Rows {
					for _, cell := range row.Cells {
						name, _ := cell.String()
						if name != "" {
							total++
							badword := models.Badword{}
							cc := models.GetNameCount(name)
							if cc > 0 {
								dupCount++
								if names == "" {
									names = name
								} else {
									names += "," + name
								}
							} else {
								badword.Name = name
								badword.Status = int8(1)
								if id, ok := userId.(int); ok {
									badword.Creator = id
								}
								badword.CreateTime = time.Now()
								models.AddBadword(&badword)
							}
						}

					}
				}
			}
		}
		c.Data["total"] = total
		c.Data["dupCount"] = dupCount
		c.Data["realCount"] = total - dupCount
		c.Data["names"] = names
	} else {
		c.Data["err"] = "err"
	}
	c.Layout = "layout/layout.html"
	c.TplName = "badword/layer.html"
}

//delete badword
func (c *BadwordController) Delete() {
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		models.DeleteBadword(id)
		c.Redirect("/badword/index", 302)
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
}

//delete badwords
func (c *BadwordController) BatchDelete() {
	ids := c.GetString("ids")
	if ids != "" {
		ids_arr := strings.Split(ids, ",")
		for _, v := range ids_arr {
			id, _ := strconv.Atoi(v)
			models.DeleteBadword(id)
			c.Redirect("/badword/index", 302)
		}
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
}

//modify badword status
func (c *BadwordController) ModifyStatus() {
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	status := c.GetString("status")
	//初始化变量
	var st = int8(1)
	if status == "1" {
		st = 2
	} else {
		st = 1
	}
	userId := c.GetSession("userId")

	if id > 0 {
		badword := models.Badword{Id: id}
		badword.Status = int8(st)
		badword.ModifyTime = time.Now()
		if id, ok := userId.(int); ok {
			badword.Modifier = id
		}
		models.UpdateStatusById(&badword)
		c.Redirect("/badword/index", 302)
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
}

//start badwords
func (c *BadwordController) BatchStart() {
	ids := c.GetString("ids")
	userId := c.GetSession("userId")
	if ids != "" {
		ids_arr := strings.Split(ids, ",")
		for _, v := range ids_arr {
			id, _ := strconv.Atoi(v)
			badword := models.Badword{Id: id}
			badword.Status = int8(1)
			badword.ModifyTime = time.Now()
			if id, ok := userId.(int); ok {
				badword.Modifier = id
			}
			models.UpdateStatusById(&badword)
		}
		c.Redirect("/badword/index", 302)
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
}

//stop badwords
func (c *BadwordController) BatchStop() {
	ids := c.GetString("ids")
	userId := c.GetSession("userId")
	if ids != "" {
		ids_arr := strings.Split(ids, ",")
		for _, v := range ids_arr {
			id, _ := strconv.Atoi(v)
			badword := models.Badword{Id: id}
			badword.Status = int8(2)
			badword.ModifyTime = time.Now()
			if id, ok := userId.(int); ok {
				badword.Modifier = id
			}
			models.UpdateStatusById(&badword)
		}
		c.Redirect("/badword/index", 302)
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
}

func (c *BadwordController) Duplicate() {
	names := c.GetString("names")
	slice := strings.Split(names, ",")
	if names != "" {
		c.Data["PageTitle"] = "重复敏感词列表"
		var query = make(map[string]string)
		c.Data["words"] = names
		StatusList := map[int]string{0: "是否启用", 1: "是", 2: "否"}
		if v := c.GetString("name"); v != "" {
			//模糊匹配
			query["name__icontains"] = v
			c.Data["name"] = v
		}
		if v := c.GetString("creatorname"); v != "" {
			query["creatorname"] = v
			c.Data["creator"] = v
		}
		if v := c.GetString("modifiername"); v != "" {
			query["modifier"] = v
			c.Data["modifier"] = v
		}
		if v := c.GetString("status"); v != "" && v != "0" {
			query["status"] = v
		}
		if v := c.GetString("createbtime"); v != "" {
			query["CreateTime__gte"] = v
			c.Data["createbtime"] = v
		}
		if v := c.GetString("createetime"); v != "" {
			query["CreateTime__lte"] = v
			c.Data["createetime"] = v
		}

		if v := c.GetString("modifybtime"); v != "" {
			query["ModifyTime__gte"] = v
			c.Data["modifybtime"] = v
		}

		if v := c.GetString("modifyetime"); v != "" {
			query["ModifyTime__lte"] = v
			c.Data["modifyetime"] = v
		}

		pageNo, _ := c.GetInt("PageNo")
		if pageNo == 0 {
			pageNo = 1
		}
		sizePage := c.GetString("SizePage")
		s, _ := strconv.Atoi(sizePage)
		if s == 0 {
			s = 10
		}
		c.Data["SizePage"] = s
		c.Data["Page"] = models.PageBadwords(pageNo, s, query, slice)
		c.Data["StatusList"] = StatusList
		c.Data["Query"] = query
		Status, _ := strconv.Atoi(query["status"])
		c.Data["Status"] = Status
	} else {
		c.Ctx.WriteString("敏感词不存在")
	}
	c.Layout = "layout/layout.html"
	c.TplName = "badword/duplicate.html"
}
